package org.academic.texteditor.gui.component;

import java.util.List;

import javax.swing.table.AbstractTableModel;

import org.apache.commons.beanutils.PropertyUtils;

public class ModelGrid extends AbstractTableModel {

	private static final long serialVersionUID = 4232302067848254802L;

	protected String[] columns;
	protected Object[][] data;

	public ModelGrid(String... columns) {
		this.columns = columns;
	}

	public int getColumnCount() {
		return columns.length;
	}

	public int getRowCount() {
		if (data == null) {
			return 0;
		}
		return data.length;
	}

	public Object getValueAt(int row, int col) {
		if (data == null) {
			return null;
		}
		return data[row][col];
	}

	public String[] getColumns() {
		return columns;
	}

	public Object[][] getData() {
		return data;
	}

	public void setData(List<Object> listData, String... attributes) throws Exception {
		try {
			data = new Object[listData.size()][columns.length];
			for (int i = 0; i < data.length; i++) {
				Object obj = listData.get(i);
				for (int j = 0; j < columns.length; j++) {
					data[i][j] = PropertyUtils.getProperty(obj, attributes[j]);
				}
			}
		} catch (Exception e) {
			throw new Exception("Houve um problema ao carregar os dados: " + e.getMessage(), e);
		}
	}

	@Override
    public String getColumnName(int col) {
	    return columns[col];
    }

	@Override
    public void setValueAt(Object value, int row, int col) {
		data[row][col] = value;
	}

	@Override
	public boolean isCellEditable(int row, int col) {
		return false;
	}

}

